/**
 *
 */
package com.sihai.ehr.web.action.ajax;

import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.web.action.EHRAction;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author wxn
 * @since 12-5-29 21:24
 */
public class OrganizationAction extends EHRAction {

    private static final long serialVersionUID = 2121333028480225454L;

    @BeanInject
    private OrganizationService organizationService;

    private boolean result;
    
    private Long parentId;
    private List<Organization> organizations;
    private Organization organization;
    
    @Action(value = "/ajax/organization-children", results = {
            @Result(name = "success", type = "json", params = {"root", "organizations"})
    })
    public String findChildren() {
        organizations = organizationService.findChildren(parentId, false, null, null);
        if (parentId == null && organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
				String sPath = getCurrentUser().getWork().getOrganization().getTreePath();
				if(sPath != null && sPath.length() > 0){
					sPath = sPath.substring(1);
					sPath = sPath.substring(0,sPath.indexOf(","));
				}
            	Long topOrgId = sPath != null && sPath.length() > 0 ? Long.parseLong(sPath) : 0L;
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId().longValue() != topOrgId.longValue()){
            			it.remove();
            		}
            	}
            }
		}
        return SUCCESS;
    }

    @Action(value = "/ajax/organization-top", results = {
            @Result(name = "success", type = "json", params = {"root", "organizations"})
    })
    public String findChildrenByTop() {
        organizations = organizationService.findChildrenByTop(parentId, null, null);
        List<Organization> orgs = new ArrayList<Organization>();
        getChrildren(organizationService.get(parentId), orgs, 1);
        organizations = orgs;
        Organization o = organizationService.get(parentId);
        organizations.add(0, new Organization(o.getId(), "├ "+o.getFullName()));
        sout();
        return SUCCESS;
    }
    private void getChrildren(Organization org, List<Organization> orgs, int level){
        if(organizations != null && organizations.size() > 0){
            for(Organization o : organizations){
                if(o.getParent().getId().longValue() == org.getId().longValue()){
                    String temp = "";
                    if(level == 1){
                        temp = "&#12288;";
                    }else if(level > 1){
                        StringBuffer sb = new StringBuffer();
                        for(int i=0; i<level;i++){
                            sb.append("&#12288;");
                        }
                        temp = sb.toString();
                    }
                    orgs.add(new Organization(o.getId(), temp+"├ "+o.getFullName()));
                    getChrildren(o, orgs, level + 1);
                }
            }
        }
    }

    private void sout(){
        for(Organization o : organizations){
            System.out.println(o.getId()+"---wxn---"+o.getFullName());
        }
    }

    @Action(value = "/ajax/organization-current", results = {
            @Result(name = "success", type = "json", params = {"root", "organization"})
    })
    public String getCurrent() {
        organization = organizationService.get(parentId);
        if(organization != null){
            Organization t = new Organization();
            t.setFullName(organization.getTopOrganization() == null ? "" : organization.getTopOrganization().getFullName());
            t.setId(organization.getTopOrganization() == null ? 0 : organization.getTopOrganization().getId());
            Organization p = new Organization();
            p.setFullName(organization.getParent() == null ? "" : organization.getParent().getFullName());
            p.setId(organization.getParent() == null ? 0 : organization.getParent().getId());
            organization.setTopOrganization(t);
            organization.setParent(p);
        }
        
        return SUCCESS;
    }

    @Action(value = "/ajax/organization-top-workno", results = {
            @Result(name = "success", type = "json", params = {"root", "organization"})
    })
    public String getTopWorkNo() {
        organization = organizationService.get(parentId);
        Organization top = organization.getTopOrganization();
        String workNo = (top == null ? organization.getEmployeeNo() : top.getEmployeeNo());
        Long oid = (top == null ? organization.getId() : top.getId());
        organization = new Organization();
        organization.setEmployeeNo(workNo);
        organization.setId(oid);
        return SUCCESS;
    }

    //删除
    @Action(value = "/organization/remove", results = {
            @Result(name = "success", type = "json", params = {"root", "result"})
    })
    public String remove() {
        try{
            organizationService.remove(organizationId);
            result = true;
        }catch (Exception e){
            result = false;
        }

        return SUCCESS;
    }

    //移动
    @Action(value = "/ajax/organization-move", results = {
            @Result(name = "success", type = "json", params = {"root", "result"})
    })
    public String move() {
        Long moveId = NumberUtils.createLong(getParameter("move_id")); //移动的对象id
        Long newParentId = NumberUtils.createLong(getParameter("new_parent_id"));//移动到
        Organization o = organizationService.get(moveId);
        Organization p = organizationService.get(newParentId);
        if(o != null && p != null){
            o.setParent(p);
            organizationService.save(o);
            result = true;
        }

        return SUCCESS;
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public void setOrganizations(List<Organization> organizations) {
        this.organizations = organizations;
    }

    public Organization getOrganization() {
        return organization;
    }

    public void setOrganization(Organization organization) {
        this.organization = organization;
    }

    public boolean isResult() {
        return result;
    }
}
